package com.loan.market.util

import java.util.Base64
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.spec.SecretKeySpec

const val MAPKETPLACE_SECRET_KEY: String = "T4P5tKIcZGAsHNyFoUPZNCEcDkS3uX1OBVzY+HWAT5U="
private const val ALGORITHM = "AES"
private const val CHARSET = "UTF-8"

fun String.encrypt(): String {
    val cipher = Cipher.getInstance(ALGORITHM)
    cipher.init(Cipher.ENCRYPT_MODE, base64DecodedSecretKey(MAPKETPLACE_SECRET_KEY))
    val encryptedBytes = cipher.doFinal(toByteArray(charset(CHARSET)))
    return Base64.getEncoder().encodeToString(encryptedBytes)
}

fun String.decrypt(): String {
    val cipher = Cipher.getInstance(ALGORITHM)
    cipher.init(Cipher.DECRYPT_MODE, base64DecodedSecretKey(MAPKETPLACE_SECRET_KEY))
    val decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(this))
    return String(decryptedBytes, charset(CHARSET))
}

fun base64DecodedSecretKey(encodedSecretKey: String?): SecretKey {
    val decodedBytes = Base64.getDecoder().decode(encodedSecretKey)
    return SecretKeySpec(decodedBytes, ALGORITHM)
}
